package sampletest.googlecode.genericdao.oldworld.model;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import sample.googlecode.genericdao.oldworld.dao.UserDAO;
import sample.googlecode.genericdao.oldworld.model.User;

import junit.framework.TestCase;

public class UserTest extends TestCase {
	 private ApplicationContext factory;
	 public UserTest(String s)
	    {
	        super(s);
	        //factory = new ClassPathXmlApplicationContext("test-applicationContext.xml");
	        factory = new ClassPathXmlApplicationContext("applicationContext-persistence.xml");
	    }
	 public void testCrud() throws Exception{
		 UserDAO userDao=this.getUserDao();
		 User user=new User();
		 user.setUserAge(Integer.valueOf(10).shortValue());
		 user.setUserName("test");
		 userDao.save(user);
	 }
	 private void openSession()
	    {
	        SessionFactory sessionFactory = getSessionFactory();
	        Session session = SessionFactoryUtils.getSession(sessionFactory, true);
	        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
	    }

     private void closeSession()
     {
        SessionFactory sessionFactory = getSessionFactory();
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
        sessionHolder.getSession().flush();
        sessionHolder.getSession().close();
        SessionFactoryUtils.releaseSession(sessionHolder.getSession(), sessionFactory);
     }

	 private void restartSession()
	 {
        closeSession();
        openSession();
	 }

     private SessionFactory getSessionFactory()
     {
        return (SessionFactory) factory.getBean("sessionFactory");
     }

     private UserDAO getUserDao()
     {
    	 UserDAO userDao = (UserDAO) factory.getBean("UserDAO");
        return userDao;
     }
}
